import { Component, OnInit } from '@angular/core';

import { Http } from '@angular/http';

import{ Channel } from '../../utils/channel';

import { AlertsService } from '../../modules/ng2-alerts';

import { Router } from '@angular/router';

@Component({
  selector: 'app-reg',
  templateUrl: './reg.page.html',
  styleUrls: ['./reg.page.css'],
  providers:[Channel]
})
export class RegPage implements OnInit {

  // 登录错误提示
  public error:boolean = false;

  // user
  public user:any;

  public source:any;

  eventOff:any;

  constructor(private channel:Channel,private http:Http,private _alert:AlertsService,private router:Router) { }

  ngOnInit() {

    // user
    this.user = {
      nick : '',
      code:'',
      codeText:'获取验证码',
      password:'',
      channel: 0,
      nickError:false,
      codeError:false
    };

    this.source = this.channel.init();

    this.user.channel = this.source.channel;
  }

  ngOnDestroy(){
    if(this.eventOff){
      this.eventOff.unsubscribe();
    }
  }


  // 获取验证码
  getCode(){
    if(this.user.nickError){
      this.user.nickError = false;
    }
    this.user.codeText = '60秒...';
    this.time();

    this.http.post('/qbmf/sendVerifySMS',{
      type:0,
      phone:this.user.nick,
      channel:this.user.channel
    }).subscribe((res:any)=>{
      // console.log(res);

    },(err:any)=>{
      // console.log(err);
      // this._alert.create('info',  err.error.msg);
      this.user.nickError = true;

    });



    return false;
  }

  // 倒计时
  timeLimit = 60;
  time(){
    setTimeout(()=>{

      this.timeLimit -=1;


      if(this.timeLimit >0 ){

        this.user.codeText = this.timeLimit+'秒...';

        this.time();
      }else{
        this.user.codeText = "获取验证码";
        this.timeLimit = 60;
      }


    },1000);
  }

  submit(){

    if(this.user.codeError){
      this.user.codeError = false;
    }
    this.eventOff = this.http.post('/qbmf/signUp',{
      nick: this.user.nick,
      code:this.user.code,
      password: this.user.password,
      channel:this.user.channel
    }).subscribe((res:any)=>{
      // console.log(res);

      this._alert.create('success', "注册成功");

      setTimeout(() => {
        this.router.navigate(['/login']);
      }, 1000);

    },(err:any)=>{
      // console.log(err);
      //
      this.user.codeError = true;

    });
  }


}
